var rootPath = getRootPath();
var x,y,width,height,photo,oriFinalImg;
$(function() {
	let imgList = $(".right .imgList");
	$(".right .imgList").each(function(index,item){
		$(this).click(function(){
			var finalImgSrc = $(this).find("img").attr("src")
			$("#finalImg").attr("src",finalImgSrc);
			
			//头像图片为url
			if(finalImgSrc.indexOf("moren.png") == -1) {
				photo = (getParam($(this).find("img").attr("src"), "fileName") == null ? finalImgSrc : getParam($(this).find("img").attr("src"), "fileName"));
			}
		});
	});

	$.ajax({
		url : rootPath + '/userDetailFront/queryDetail',
		type : 'GET',
		contentType : 'application/json;charset=UTF-8',
		success : function(data) {
			if(data != null && data.returnObject != null && data.returnObject.user != null) {
				if(data.returnObject.user.headimgurl == null || data.returnObject.user.headimgurl == '') {					
					$("#finalImg").attr("src", "../../images/moren.png");
				} else {
					$("#finalImg").attr("src",rootPath + "/file/viewimg?fileName=" + (data.returnObject.user.headimgurl) + "&type=1");
				}
				$('#headerAva', parent.document).attr("src",$("#finalImg").attr('src'));
				
				oriFinalImg = $("#finalImg").attr("src");
				
				for (var i = 1; i < 4; i++) {
					if(data.returnObject['photo' + i] == null || data.returnObject['photo' + i] == '') {
						$("#photo" + i).attr("src", "../../images/moren.png");
					} else {
						$("#photo" + i).attr("src",rootPath + "/file/viewimg?fileName=" + (data.returnObject['photo' + i]) + "&type=1");							
					}
				}
			}
		},
		error : function(jqXHR, textStatus, errorThrown) {
			layer.alert("error");
		}
	});

	 //弹出框水平垂直居中
    (window.onresize = function () {
        var win_height = $(window).height();
        var win_width = $(window).width();
        let clientHeight = document.body.clientHeight;
        if (win_width <= 768){
            $(".tailoring-content").css({
                "top": (clientHeight-340)/2,
                "left": 0
            });
        }else{
            $(".tailoring-content").css({
            	"top": 100,
                "left": (win_width - $(".tailoring-content").outerWidth())/2
            });
        }
    })();

    //弹出图片裁剪框
    $("#replaceImg").on("click",function () {
        $(".tailoring-container").toggle();
    });
   
    //cropper图片裁剪
    $('#tailoringImg').cropper({
    	viewMode: 1,
        aspectRatio: 1/1,//默认比例
        preview: '.previewImg',//预览视图
        guides: false,  //裁剪框的虚线(九宫格)
        autoCropArea: 0.5,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        movable: false, //是否允许移动图片
        dragCrop: true,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        movable: true,  //是否允许移动剪裁框
        resizable: true,  //是否允许改变裁剪框的大小
        zoomable: false,  //是否允许缩放图片大小
        mouseWheelZoom: true,  //是否允许通过鼠标滚轮来缩放图片
        touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
        rotatable: true,  //是否允许旋转图片
        crop: function(e) {
            // 输出结果数据裁剪图像。
        	x = parseInt(e.x);
        	y = parseInt(e.y);
        	width = parseInt(e.width);
        	height = parseInt(e.height);
        }
    });
    //旋转
    $(".cropper-rotate-btn").on("click",function () {
        $('#tailoringImg').cropper("rotate", 45);
    });
    //复位
    $(".cropper-reset-btn").on("click",function () {
        $('#tailoringImg').cropper("reset");
    });
    //换向
    var flagX = true;
    $(".cropper-scaleX-btn").on("click",function () {
        if(flagX){
            $('#tailoringImg').cropper("scaleX", -1);
            flagX = false;
        }else{
            $('#tailoringImg').cropper("scaleX", 1);
            flagX = true;
        }
        flagX != flagX;
    });

    //裁剪后的处理
    $("#sureCut").on("click",function () {
        if ($("#tailoringImg").attr("src") == null ){
            return false;
        } else {
        	
        	 var transformMatrix = $(".cropper-crop-box").css("-webkit-transform") ||
        	 $(".cropper-crop-box").css("-moz-transform")    ||
        	 $(".cropper-crop-box").css("-ms-transform")     ||
        	 $(".cropper-crop-box").css("-o-transform")      ||
        	 $(".cropper-crop-box").css("transform");
        	 var matrix = transformMatrix.replace(/[^0-9\-.,]/g, '').split(',');
        	 var x = matrix[12] || matrix[4]; //translate x
        	 var y = matrix[13] || matrix[5]; //translate y
        	
            var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
            var base64url = cas.toDataURL('image/jpeg'); //转换为base64地址形式
            $("#finalImg").attr("src",base64url);//显示为图片的形式
            //关闭裁剪框
            closeTailor();
        }
    });
    
    $("#save").click(function() {
    	var base64url = $("#previewImg img").attr("src");
    	showLoading();
    	$.ajax({
    		url : rootPath + '/userDetailFront/updatePhoto',
    		type : 'POST',
    		contentType : 'application/json;charset=UTF-8',
    		data : 	JSON.stringify({
    			"base64url" : $("#previewImg img").attr('src'),
    			"x" : x,
    			"y" : y,
    			"width" : width,
    			"height" : height,
    			"photo" : photo
    		}),
    		success : function(data) {
    			hideLoading();
    			if(data != null && "0000" == data.returnCode) {
    				layer.msg("头像保存成功",{time:1000,icon:6},function() {
    					parent.$("#content").prop("src", "headImgSetting.html");
    				});
    				/*$('#headerAva', parent.document).attr("src",$("#previewImg img").attr('src'));*/
    			} else {
    				layer.alert(data.returnMessage);
    			}
    		},
    		error : function(jqXHR, textStatus, errorThrown) {
    			hideLoading();
    			layer.alert("error");
    		}
    	});
    });
 
});
//获取历史图像作头像
function getOldImg(){
	
}

//图像上传
function selectImg(file) {
    if (!file.files || !file.files[0]){
        return;
    }
    
    if(!checkFileExt(file.value)) {
    	layer.alert("头像只支持jpg、png、jpeg格式的图片");
    	return;
    }
    
    var reader = new FileReader();
    reader.onload = function (evt) {
        var replaceSrc = evt.target.result;
        //更换cropper的图片
        $('#tailoringImg').cropper('replace', replaceSrc,false);//默认false，适应高度，不失真
    }
    reader.readAsDataURL(file.files[0]);
}

//关闭裁剪框
function closeTailor() {
    $(".tailoring-container").toggle();
}